package com.honeyms.project.im.email.service.impl;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.honeyms.framework.web.domain.AjaxResult;
import com.honeyms.project.im.email.service.EmailService;

@Service
public class EmailServiceImpl implements EmailService {


	@Autowired
	JavaMailSender javaMailSender;
	
	@Value("${spring.mail.username}")
    private String username;
	
	/**
     * 发送邮件
     *
     * @param subject        主题
     * @param body           内容
     * @param html           是否为html格式
     * @param from           发件人
     * @param cc             抄送人[多个]
     * @param to             收件人[多个]
     * @param attachPathList 附件路径
     */
	@Override
	public AjaxResult sendemail(String address,String text){
		
		String theme="来自于HoneyBlog(好呢博客)的回复!";
        //发邮件
        SimpleMailMessage message = new SimpleMailMessage();
        //发件人邮件地址(上面获取到的，也可以直接填写,string类型)
        message.setFrom(username);
        //收件人邮件地址
        message.setTo(address);
        //邮件主题
        message.setSubject(theme);
        //邮件正文
        message.setText(text);
        try {
        	javaMailSender.send(message);
		} catch (Exception e) {
			return AjaxResult.error(e.toString());
		}
        return AjaxResult.success();
	}
	
	@Override
	public AjaxResult sendhtmlemail(String address,String text){
		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
	    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
	    try {
	    	messageHelper.setSubject("来自于HoneyBlog(好呢博客)的回复!");
			messageHelper.setFrom(username);
			messageHelper.setTo(address);
		    messageHelper.setText(text, true);
		} catch (MessagingException e) {
			return AjaxResult.error(e.toString());
		}
	    javaMailSender.send(messageHelper.getMimeMessage());
		return AjaxResult.success();
	}

}
